import config.globalVariable as Gv
import api.kaipanla.KaiPanLaAPI as kplAPI
import pathlib
import json


def get_data(num,date):
    if date is None:
        return
    plate_data_all = kplAPI.getPlateData()
    if plate_data_all is None:
        return
    list = []
    for parent_index,parent_row in plate_data_all.iterrows():
        code = parent_row['股票代码']
        ZSName = parent_row['板块']
        ZSPop = parent_row['人气']
        obj = {'ZSCode':code,'ZSName':ZSName,'TCExplain':'',}
        StockList = []
        plate_data_sub_all,upNum =kplAPI.getPlateSubData(num,code)
        if plate_data_sub_all is None:
            return
        for child_index,child_row_code_sub in plate_data_sub_all.iterrows():
            sub_list = []
            sub_list.append(child_row_code_sub['股票代码'])
            sub_list.append(child_row_code_sub['股票名称'])
            sub_list.append(None)
            sub_list.append(None)
            sub_list.append(child_row_code_sub['涨幅'])
            StockList.append(sub_list)
        obj['StockList'] = StockList
        obj['num'] = upNum
        obj['ZSPop'] = ZSPop
        list.append(obj)
    result_map = {}
    result_map[date] = list
    return result_map


def bkld_function(num,current_time):
    '''执行板块轮动定时任务'''
    print('----将人气数据写入板块------')
    #{2023-12-29:[value]}
    jsonfileaddr = pathlib.Path(__file__).parent.parent.resolve().as_posix() + '/' + Gv.platepopdataaddr
    #读取文件
    data = {}
    try:
        with open(jsonfileaddr, 'r') as f:
            data = json.load(f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Error reading JSON file: {e}")

    dateStr = current_time
    requestData = data.get(dateStr)
    if requestData is not None:
        return

    request_dataAll = get_data(num,current_time)
    if request_dataAll is None:
        return

    if requestData is None:
        first_key = next(iter(request_dataAll))
        oldData = data.get(first_key)
        if oldData is not None:
            current_time = first_key
            return
        dateStr = first_key
        requestData = request_dataAll.get(dateStr)
    else:
        return
    current_time = dateStr
    data[dateStr] = requestData
    #写入文件
    try:
        with open(jsonfileaddr, 'w') as f:
            json.dump(data,f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Error reading JSON file: {e}")